import 'package:bluetooth/bluetooth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class PeripheralList extends StatefulWidget {
  const PeripheralList({Key? key}) : super(key: key);

  @override
  _PeripheralListState createState() => _PeripheralListState();
}

class _PeripheralListState extends State<PeripheralList> {
  List datas = [];

  @override
  void initState() {
    super.initState();
    Bluetooth.connect('BarCode Scanner BLE', showLog: true);
    Bluetooth.addEventHandler(
        onDiscoverPeripheral: (Map<String, dynamic> message) async {
          setState(() {
            datas.add(message["name"]);
          });
        },
        onUpdateState: (Status state) async {
            print("状态变化 $state");
        }
    );
  }

  @override
  void dispose() {
    super.dispose();
    Bluetooth.stop();
  }


  @override
  Widget build(BuildContext context) {
    return  Scaffold(
        appBar: AppBar(title: Text("Peripheral List")),
         body: ListView.builder(
            itemBuilder: _cellForRow, itemCount: datas.length)
    );
  }

  Widget _cellForRow(BuildContext context, int index) {
    return GestureDetector(
      onTap: (){
          Bluetooth.connectPeripheral(datas[index]);
      },
      child: Container(
        height: 50,
        padding: EdgeInsets.all(10),
        color: index % 2 == 0 ?Colors.green : Colors.blue,
        child: Row(
          children: [
            Text(datas[index],style: TextStyle(fontSize: 18),)
          ],
        ),
      ),
    );
  }
}
